import { useEffect, useMemo, useState } from 'react';
import { useResize } from '../../../common/hooks/useResize';
import { searchOrderByIds, getFieldConfig, searchOrderShipByIds, updateFieldConfig } from './services';
import { findIndex, uniqueId } from 'lodash';
import { loadScript } from '@/utils/utils.jsx';
import HeaderActions from '../Actions/index';
import RightAction from './components/RightAction';
import TableList from './components/TableList';
import FooterInfo from './components/FooterInfo';
import CommonPagination from '@/components/CommonPagination';
import CommonLoading from '@/components/CommonLoading';
import { initColumnsConfig } from './components/ColumnSet/initColumns';
import styles from './index.module.less';

//请求保存的列
const pageConfigCode = {
	'sysOrder': 'orderListPageConfig',
	'payOrder': 'orderListPageConfig',
	'history': 'orderListPageConfig',
	'orderShip': 'orderShipPageConfig',
}

//获取当前订单状态集合
const getOrderStates = (actions, type, form) => {
	const orderShipMap = {
		'1': 10,
		'2': 20,
		'3': 40,
		'4': 50,
	}
	if(actions == 'orderShip') {
		return type == 1 ? [10, 30, 51, 52] : [orderShipMap[type]];
	} else {
		return form.stateArr;
	}
}

//订单列表
const OrderList = (props) => {

	const { type, actions, extraHeight = 0, filterSize, tableHeader, ajaxFn, getHotStatisticsFunc,  form } = props;

	//初始化列表
	const initColumns = initColumnsConfig[actions];

	//表格顶部右侧排序
	const [sortField, setSortField] = useState({
		sortBy: 'ecPayTime',
		sortType: false
	})

	//付款中订单数量统计
	const [payOrderCount, setPayOrderCount] = useState(0);

	//列表数据
	const [orderList, setOrderList] = useState([]);

	const [loading, setLoading] = useState(false);

	//当前选中的key
	const [selectKeys, setselectKeys] = useState([]);

  const [id] = useState(uniqueId('webww'));

	const [pageConfig, setPageConfig] = useState({
		columns: initColumns,//订单列数据
		isExistWeight: false,//操作设置，是否读取订单重量
	})

	//列表分页
	const [pages, setPages] = useState({
		current: 1,
		total: 0,
		pageSize: 500,
		pageSizeOptions: [100, 200, 500],
	});

	//监听变更
	const { el: headerEl, height: headerHeight, onResize } = useResize();

	const searchForm = useMemo(() => {
		return {
			...form,
			...sortField,
		};
	}, [form, sortField]);

	useEffect(() => {
		getPageConfig();
    loadScriptFunc();
	}, [])

	const loadScriptFunc = async () => {
		setLoading(true);
    const webwwDependencies = {
      kissy: 'https://assets.alicdn.com/s/kissy/1.2.0/kissy-min.js',
      webww: 'https://market.m.taobao.com/app/aliww/bc-ww/webww',
    };
    await loadScript(webwwDependencies.kissy);
    await loadScript(webwwDependencies.webww);
    setTimeout(()=>{
			window?.Light?.init(id);
		  setLoading(false);
		},800);
  }

	useEffect(() => {
		onResize();
	}, [filterSize])

	useEffect(() => {
		if (pages.current == 1) {
		  setOrderList([]);
			queryOrderList();
		} else {
			setPages({
				...pages,
				current: 1
			})
		}
	}, [searchForm])


	useEffect(() => {
		setOrderList([]);
		queryOrderList();
	}, [pages.current, pages.pageSize])

	//获取页面的配置信息
	const getPageConfig = async () => {
		setLoading(true);
		const params = {
			code: pageConfigCode[actions],
		}
		const { success, data = {} } = await getFieldConfig(params);
		if (success) {
			const { param = '' } = data;
			if (param) {
				setPageConfig(JSON.parse(param));
			}
		}
		setLoading(false)
	}

	//更新配置文件
	const updatePageConfig = async (keys, val, cb) => {
		const obj = {
			...pageConfig,
			[keys]: val
		}
		const { success } = await updateFieldConfig({
			code: pageConfigCode[actions],
			param: JSON.stringify(obj)
		});
		if (success) {
			setPageConfig(obj);
		}
		cb && cb(success);
	}

	//获取订单列表
	const queryOrderList = async () => {
		if(searchForm.isLimit) return;
		delete searchForm.isLimit;
		setLoading(true);
		const params = {
			...searchForm,
			pageNum: pages.current,
			pageSize: pages.pageSize,
		}
		const { success, data } = await ajaxFn(params);
		if (success) {
			const { records, total } = data;
			setPages({
				...pages,
				total: total
			})
			setOrderList(records);
			setselectKeys([]);
			setTimeout(()=>{
				window?.Light?.init(id);
			},800);
		}
		setLoading(false)
	}

	/**
	 * 更换数据
	 * @param {*} arr 更新后的订单数组
	 * @param {*} isCount //是否需要请求统计信息，默认不用1，需要2
	 */
	const replaceData = (arr) => {
		//做出处理
		const arr1 = [...orderList];
		let arr2 = [...selectKeys], total = pages.total;
		//先判断状态是否进行流转
		for (let i in arr) {
			const item = arr[i];
			const index = findIndex(arr1, ['id', item.id]);
			const orderStates = getOrderStates(actions, type, form);
			if((actions == 'payOrder' && item.payState == 1) || (orderStates?.length && !orderStates.includes(item.state))){//待支付订单刷新 抹除行、勾选、总条数
				total -= 1;
        arr1.splice(index, 1);
				arr2 = arr2.filter(childId => item.id != childId);
			}else{
				arr1[index] = item;
			}
		}
		setOrderList(arr1);
		setselectKeys(arr2);
		setPages({...pages, total});
	};

	//对于拆单和合单情景，需要新增数据
	const replaceAddData = (arr) => {
		const orderStates = getOrderStates(actions, type, form);
		const index = findIndex(orderList, ['id', selectKeys[0]]);

		const list = [];//更新后的数据
		const list1 = [];//存储id集合进行选择
		for(let i in arr) {
			const item = arr[i];
			if(orderStates.includes(item.state)) {
				list.push(item);
				list1.push(item.id);
			}
		}
		const arr1 = [...orderList];
		const total = pages.total + (list.length - 1);
		arr1.splice(index, 1, ...list);
		setOrderList(arr1);
		setselectKeys(list1);
		setPages({...pages, total});
	}

	//接口级别更新数据,局部刷新,isNew:是否会产生新订单，适用于拆单和合单逻辑
	const handleGetData = async (ids, isNew) => {
		setLoading(true);
		const resetApi = actions == 'orderShip' ? searchOrderShipByIds : searchOrderByIds;
		const { data, success } = await resetApi(ids || selectKeys);
		if (success) {
			if(isNew) {
				replaceAddData(data);
			} else {
				console.log(data,'data')
				replaceData(data);
			}
		}
		setLoading(false);
	};


	//订单操作后处理
	const handleOk = (updateType = 1, data, paymentStatistics) => {
		//操作成功之后更新菜单信息
		if (updateType == 1) {
			if ((!data || !data.length) && !selectKeys.length) return;
			handleGetData(data);
		} else if (updateType == 2) {
			queryOrderList();
			//存在统计信息需要重新请求
			getHotStatisticsFunc && getHotStatisticsFunc();
		} else if(updateType == 3) {
			//是否产生新订单
			handleGetData(data, true);
		}
		if (paymentStatistics) {
			setPayOrderCount(paymentStatistics);
		}
	}

	//菜单信息
	const AcitonProps = {
		operationPage: actions,
		pageConfig,
		type,
		searchForm,
		selectKeys,
		orderList,
		handleOk,
		updatePageConfig
	}

	//右侧操作区
	const RightActionProps = {
		actions,
		initColumns,
		realColumns: pageConfig.columns,
		setSortField,
		updatePageConfig,
	}

	//表格区域
	const TableListProps = {
		actions,
		orderList,
		selectKeys,
		realColumns: pageConfig.columns,
		headerHeight: headerHeight + extraHeight,
		setselectKeys,
		handleOk,
		updatePageConfig
	}

	//底部信息
	const FooterInfoProps = {
		payOrderCount,
		setPayOrderCount
	}

	//分页数据
	const pageProps = {
		pagination: pages,
		selectTotal: selectKeys.length,
		handleChange(current, size) {
			const obj = { ...pages, current, pageSize: size };
			setPages(obj);
		},
	};


	return (
		<>
			<div ref={headerEl} >
				{tableHeader && <div className={styles.header}>{tableHeader}</div>}
				<div className={styles.table_header} >
					<HeaderActions {...AcitonProps} />
					<RightAction {...RightActionProps} />
				</div>
			</div>
			<TableList {...TableListProps} />
			<div className={styles.footerInfo}>
				<FooterInfo {...FooterInfoProps} />
				<CommonPagination {...pageProps} />
			</div>
			<CommonLoading loading={loading} />
		</>
	);
};

export default OrderList;
